package com.weetop.akly.activity.mine;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.classic.adapter.BaseAdapterHelper;
import com.classic.adapter.CommonRecyclerAdapter;
import com.qmuiteam.qmui.widget.dialog.QMUIBottomSheet;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.weetop.akly.R;
import com.weetop.akly.activity.meessage.ShenpiDetailActivity;
import com.weetop.akly.base.BaseFragment;
import com.weetop.akly.base.mvp.BaseModel;
import com.weetop.akly.base.mvp.BaseObserver;
import com.weetop.akly.base.mvp.BasePresenter;
import com.weetop.akly.bean.ApproveItem;
import com.weetop.akly.bean.BaseCountBean;
import com.weetop.akly.bean.PostMessage;
import com.weetop.akly.utils.BaseUtils;
import com.weetop.akly.utils.KeyBoardUtils;

import java.util.ArrayList;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

public class ApplyListFragment extends BaseFragment {

    private static final String MODE_ID = "MODE_ID";
    @BindView(R.id.et_search)
    EditText etSearch;
    @BindView(R.id.rv_record)
    RecyclerView rvRecord;
    @BindView(R.id.tv_type)
    TextView typeView;
    @BindView(R.id.tv_status)
    TextView statusView;
    @BindView(R.id.ll_status)
    View statusClickView;
    @BindView(R.id.ll_type)
    View typeClickView;
    @BindView(R.id.srl_apply_record)
    SmartRefreshLayout srlApplyRecord;
    private Unbinder unbinder;
    private String modeId;
    private int page = 1;
    private boolean isLoadMore = false;
    private boolean isRefresh = false;
    private String keywords = "";
    private CommonRecyclerAdapter<ApproveItem> adapter;
    private ArrayList<ApproveItem> data;
    private ArrayList<String> typeList = new ArrayList<>();
    private ArrayList<String> statusList = new ArrayList<>();
    private String askLeaveType;
    private String askLeaveStatus;

    private boolean isViewCreated; // 界面是否已创建完成
    private boolean isVisibleToUser; // 是否对用户可见
    private boolean isDataLoaded; // 数据是否已请求
    private String type;

    public static ApplyListFragment instance(String modeId, String type) {
        ApplyListFragment fragment = new ApplyListFragment();
        Bundle bundle = new Bundle();
        bundle.putString(MODE_ID, modeId);
        bundle.putString("type", type);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = View.inflate(getActivity(), R.layout.fragment_apply_list, null);
        unbinder = ButterKnife.bind(this, view);
        modeId = getArguments().getString(MODE_ID);
        type = getArguments().getString("type");
        initQjlx();
        initQjStatus();
        initView();
        tryLoadData();

        return view;
    }

    private QMUIBottomSheet chooseGroupSheet;

    private void initQjlx() {
        typeList.clear();
        typeList.add("全部类型");
        typeList.add("年假");
        typeList.add("事假");
        typeList.add("病假");
        typeList.add("婚假");
        typeList.add("产假");
        typeList.add("陪产假");
        typeList.add("工伤假");

        askLeaveType = typeList.get(0);
        typeView.setText(askLeaveType);
        //初始化考勤组弹窗
        QMUIBottomSheet.BottomListSheetBuilder chooseHeadImgBottomSheetBuilder = new QMUIBottomSheet.BottomListSheetBuilder(getActivity());
        for (String datum : typeList) {
            chooseHeadImgBottomSheetBuilder.addItem(datum);
        }
        chooseHeadImgBottomSheetBuilder.setOnSheetItemClickListener((dialog, itemView, position, tag) -> {
            askLeaveType = typeList.get(position);
            typeView.setText(askLeaveType);
            dialog.dismiss();
            isRefresh = true;
            page = 1;
            getSpRecord(page + "", keywords);
        });
        chooseGroupSheet = chooseHeadImgBottomSheetBuilder.build();
    }

    private QMUIBottomSheet chooseGroupSheetStatus;

    private void initQjStatus() {
        statusList.clear();
        statusList.add("全部状态");
        statusList.add("审核不通过");
        statusList.add("待审核");
        statusList.add("审核通过");

        askLeaveStatus = statusList.get(0);
        statusView.setText(askLeaveStatus);
        //初始化考勤组弹窗
        QMUIBottomSheet.BottomListSheetBuilder chooseHeadImgBottomSheetBuilder = new QMUIBottomSheet.BottomListSheetBuilder(getActivity());
        for (String datum : statusList) {
            chooseHeadImgBottomSheetBuilder.addItem(datum);
        }
        chooseHeadImgBottomSheetBuilder.setOnSheetItemClickListener((dialog, itemView, position, tag) -> {
            askLeaveStatus = statusList.get(position);
            statusView.setText(askLeaveStatus);
            dialog.dismiss();
            isRefresh = true;
            page = 1;
            getSpRecord(page + "", keywords);
        });
        chooseGroupSheetStatus = chooseHeadImgBottomSheetBuilder.build();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        isViewCreated = true;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        this.isVisibleToUser = isVisibleToUser;
    }

    public void tryLoadData() {
//        if (isViewCreated && isVisibleToUser && !isDataLoaded) {
            getSpRecord(page + "", keywords);
//            isDataLoaded = true;
//        }
    }

    private void initView() {
        if (StringUtils.equals("2", modeId)) {
           typeClickView.setVisibility(View.VISIBLE);
        } else if (StringUtils.equals("3", modeId)) {
            typeClickView.setVisibility(View.GONE);
        } else if (StringUtils.equals("4", modeId)) {
            typeClickView.setVisibility(View.GONE);
        } else if (StringUtils.equals("5", modeId)) {
            typeClickView.setVisibility(View.GONE);
        }
        statusClickView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                chooseGroupSheetStatus.show();
            }
        });
        typeClickView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                chooseGroupSheet.show();
            }
        });
        etSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    performSearch(etSearch);
                    return true;
                }
                return false;
            }
        });
        data = new ArrayList<>();
        CommonRecyclerAdapter<ApproveItem> adapter = createAdapter();
        rvRecord.setItemAnimator(null);
        rvRecord.setLayoutManager(new LinearLayoutManager(mActivity));
        rvRecord.setAdapter(adapter);
        srlApplyRecord.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                isLoadMore = true;
                page++;
                getSpRecord(page + "", keywords);
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                isRefresh = true;
                page = 1;
                getSpRecord(page + "", keywords);
            }
        });
    }


    private CommonRecyclerAdapter<ApproveItem> createAdapter() {
        adapter = new CommonRecyclerAdapter<ApproveItem>(mActivity, R.layout.item_record_apply, data) {
            @Override
            public void onUpdate(BaseAdapterHelper helper, ApproveItem item, int position) {
                //单据状态：-3删除-2撤销-1拒绝0未审核1审核中999审核通过
                // error ：#FF4C22  warning ：#FFA500  ok ：#4BCF71
                int statusBgRes = R.drawable.bg_state_errortag;
                String statusColor = "#FF4C22";
                String statusStr = "";
                switch (item.getStatus()) {
                    case 1:
                        statusBgRes = R.drawable.bg_state_oktag;
                        statusColor = "#4BCF71";
                        statusStr = "已通过";
                        break;
//                    case 1:
//                        statusBgRes = R.drawable.bg_state_warntag;
//                        statusColor = "#FFA500";
//                        statusStr = "审核中";
//                        break;
                    case 0:
                        statusBgRes = R.drawable.bg_state_warntag;
                        statusColor = "#FFA500";
                        statusStr = "未审核";
                        break;
                    case -1:
                        statusBgRes = R.drawable.bg_state_errortag;
                        statusColor = "#FF4C22";
                        statusStr = "已拒绝";
                        break;
                    case -2:
                        statusBgRes = R.drawable.bg_state_warntag;
                        statusColor = "#FFA500";
                        statusStr = "已撤销";
                        break;
                    case -3:
                        statusBgRes = R.drawable.bg_state_warntag;
                        statusColor = "#FFA500";
                        statusStr = "已删除";
                        break;
                }
//                String formatTime = BaseUtils.getTimeFormat(item.getCreate_time() + "", "MM/dd");
                helper.setText(R.id.tv_time, item.getCreate_time());
                helper.setText(R.id.tv_item_title, item.getTitle());
                TextView tvSpState = helper.getView(R.id.tv_sp_state);
                tvSpState.setText(statusStr);
                tvSpState.setTextColor(Color.parseColor(statusColor));
                tvSpState.setBackgroundResource(statusBgRes);
                LinearLayout llForm = helper.getView(R.id.ll_form);
                String tag = "";
                // model_id  1:补卡申请	2:请假申请	3:外出申请	4:外勤申请
                boolean showType = false;
                if (StringUtils.equals("2", modeId)) {
                    tag = "请假事由";
                    showType = true;
                } else if (StringUtils.equals("3", modeId)) {
                    tag = "外出事由";
                } else if (StringUtils.equals("4", modeId)) {
                    tag = "外勤事由";
                } else if (StringUtils.equals("5", modeId)) {
                    tag = "加班事由";
                }
                helper.setText(R.id.tv_reason, tag + ":" + item.getLeave_reason());
                helper.setText(R.id.tv_start_time, "开始时间：" + item.getStart_time());
                helper.setText(R.id.tv_end_time, "结束时间：" + item.getEnd_time());
                //        typeList.add("年假");
                //        typeList.add("事假");
                //        typeList.add("病假");
                //        typeList.add("婚假");
                //        typeList.add("产假");
                //        typeList.add("陪产假");
                //        typeList.add("工伤假");
                //1 年假 ，2事假 ，3病假 ，4 婚假，5产假 ，6陪产假 ，7 工伤假
                if (showType) {
                    helper.setVisible(R.id.tv_type, View.VISIBLE);
                    if (StringUtils.equals("1", item.getLeave_type())) {
                        helper.setText(R.id.tv_type, "请假类型：年假");
                    }
                    if (StringUtils.equals("2", item.getLeave_type())) {
                        helper.setText(R.id.tv_type, "请假类型：事假");
                    }
                    if (StringUtils.equals("3", item.getLeave_type())) {
                        helper.setText(R.id.tv_type, "请假类型：病假");
                    }
                    if (StringUtils.equals("4", item.getLeave_type())) {
                        helper.setText(R.id.tv_type, "请假类型：婚假");
                    }
                    if (StringUtils.equals("5", item.getLeave_type())) {
                        helper.setText(R.id.tv_type, "请假类型：产假");
                    }
                    if (StringUtils.equals("6", item.getLeave_type())) {
                        helper.setText(R.id.tv_type, "请假类型：陪产假");
                    }
                    if (StringUtils.equals("7", item.getLeave_type())) {
                        helper.setText(R.id.tv_type, "请假类型：工伤假");
                    }
                } else {
                    helper.setVisible(R.id.tv_type, View.GONE);
                }
//                helper.setText(R.id.tv_start_time, jiabanTime);
//                helper.setText(R.id.tv_end_time, "");

                ArrayList<ApproveItem.ItemsBean> items = item.getItems();
//                    llForm.removeAllViews();

//                if (items != null) {
//                    String jiabanTime = "";
//                    for (ApproveItem.ItemsBean form : items) {
//                        if (form.getForm_name().contains("原因")) {
//                            helper.setText(R.id.tv_reason, item.getLeave_reason());
//                        } else if (form.getForm_name().contains("开始时间")) {
//                            helper.setText(R.id.tv_start_time, item.getStart_time());
//                        } else if (form.getForm_name().contains("结束时间")) {
//                            helper.setText(R.id.tv_end_time, item.getEnd_time());
//                        }
//                    }
//                    if (!TextUtils.isEmpty(jiabanTime)) {
//                        helper.setText(R.id.tv_start_time, jiabanTime);
//                        helper.setText(R.id.tv_end_time, "");
//                    }
//                }
            }
        };
        adapter.setOnItemClickListener((viewHolder, view, position) -> {
            if (BaseUtils.fastClick()) {
                Intent intent = new Intent();
                ApproveItem item = data.get(position);
                item.setModel_id(modeId);
                intent.putExtra("approve_info", item);
                intent.putExtra("type", type);
                intent.putExtra("approve_id", data.get(position).getId() + "");
                BaseUtils.toActivity(mActivity, ShenpiDetailActivity.class, intent);
            }
        });
        return adapter;
    }


    private void performSearch(EditText etSearch) {
        etSearch.clearFocus();
        InputMethodManager in = (InputMethodManager) mActivity.getSystemService(Context.INPUT_METHOD_SERVICE);
        in.hideSoftInputFromWindow(etSearch.getWindowToken(), 0);
        //...perform search
        keywords = etSearch.getText().toString().trim();
//        if (!TextUtils.isEmpty(keywords)) {
        getSpRecord(page + "", keywords);
//        }
    }


    private void showDataInList(ArrayList<ApproveItem> data) {
        etSearch.setText("");
        keywords = "";
        if (isRefresh) {
            srlApplyRecord.finishRefresh(true);
            isRefresh = false;
            adapter.replaceAll(data, true);
        } else if (isLoadMore) {
            srlApplyRecord.finishLoadMore(true);
            isLoadMore = false;
            adapter.addAll(data);
        } else {
            adapter.replaceAll(data, true);
        }
    }

    public void getSpRecord(String page, String keywords) {
        Map<String, String> params = myApplication.getGlobalData();
        // model_id  1:补卡申请	2:请假申请	3:外出申请	4:外勤申请
        params.put("model_id", modeId);
        params.put("page", page);
        params.put("type", type);
        if (!StringUtils.equals(askLeaveStatus, "全部状态")) {
            if (StringUtils.equals(askLeaveStatus, "审核不通过")) {
                params.put("status", -1 + "");
            } else if (StringUtils.equals(askLeaveStatus, "待审核")) {
                params.put("status", 0 + "");
            } else {
                params.put("status", 1 + "");
            }
        }
        if (!StringUtils.equals(askLeaveType, "全部类型")) {
            params.put("leave_type", (typeList.indexOf(askLeaveType)) + "");
        }
        params.put("keywords", keywords);
        if (StringUtils.equals("2", modeId)) {
            //请假
            addDisposable(apiServer.getApproveList(params), new BaseObserver<BaseModel<BaseCountBean<ApproveItem>>>(this) {
                @Override
                public void onSuccess(BaseModel<BaseCountBean<ApproveItem>> o) {
                    data = o.getData().getList_data();
                    if (data.size() % 10 != 0) {
                        srlApplyRecord.finishLoadMoreWithNoMoreData();
                    }
                    showDataInList(data);
                }

                @Override
                public void onError(String msg) {
                    ToastUtils.showShort(msg);
                }
            });
        } else if (StringUtils.equals("3", modeId)) {
            //请假
            addDisposable(apiServer.getGoOutList(params), new BaseObserver<BaseModel<BaseCountBean<ApproveItem>>>(this) {
                @Override
                public void onSuccess(BaseModel<BaseCountBean<ApproveItem>> o) {
                    data = o.getData().getList_data();
                    if (data.size() % 10 != 0) {
                        srlApplyRecord.finishLoadMoreWithNoMoreData();
                    }
                    showDataInList(data);
                }

                @Override
                public void onError(String msg) {
                    ToastUtils.showShort(msg);
                }
            });
        } else if (StringUtils.equals("4", modeId)) {
            //请假
            addDisposable(apiServer.getWQList(params), new BaseObserver<BaseModel<BaseCountBean<ApproveItem>>>(this) {
                @Override
                public void onSuccess(BaseModel<BaseCountBean<ApproveItem>> o) {
                    data = o.getData().getList_data();
                    if (data.size() % 10 != 0) {
                        srlApplyRecord.finishLoadMoreWithNoMoreData();
                    }
                    showDataInList(data);
                }

                @Override
                public void onError(String msg) {
                    ToastUtils.showShort(msg);
                }
            });
        } else if (StringUtils.equals("5", modeId)) {
            //请假
            addDisposable(apiServer.getOverTimeList(params), new BaseObserver<BaseModel<BaseCountBean<ApproveItem>>>(this) {
                @Override
                public void onSuccess(BaseModel<BaseCountBean<ApproveItem>> o) {
                    data = o.getData().getList_data();
                    if (data.size() % 10 != 0) {
                        srlApplyRecord.finishLoadMoreWithNoMoreData();
                    }
                    showDataInList(data);
                }

                @Override
                public void onError(String msg) {
                    ToastUtils.showShort(msg);
                }
            });
        }


    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    protected boolean isRegisterEventBus() {
        return true;
    }

    @Override
    protected void receiveEvent(PostMessage event) {
        if (modeId.equals(event.getKey())) {
//            ToastUtils.showShort("接收到了消息：" + event.getKey());
            isRefresh = false;
            isLoadMore = false;
            page = 1;
            etSearch.setText("");
            keywords = "";
//            srlApplyRecord.autoRefresh();
            KeyBoardUtils.closeKeybord(mActivity);
        }
    }
}
